<template>
    <el-dialog v-model="visible" :title="data?'编辑':'添加人员'">
        <el-form :model="formData">
            <el-form-item  label="id" :label-width="120">
                <el-input v-model="formData.id" :disabled="!!formData.id" />
            </el-form-item>
            <el-form-item label="用户名" :label-width="120">
                <el-input v-model="formData.username" />
            </el-form-item>
            <el-form-item label="电话号码" :label-width="120">
                <el-input v-model="formData.phonenumber" />
            </el-form-item>
            <el-form-item label="角色" :label-width="120">
                <el-input v-model="formData.player" />
            </el-form-item>
            <el-form-item label="上级人员" :label-width="120">
                <el-input v-model="formData.manager" />
            </el-form-item>
            <el-form-item label="负责地块" :label-width="120">
                <el-input v-model="formData.land" />
            </el-form-item>
            <el-form-item label="登陆系统时间" :label-width="120">
                <el-date-picker v-model="formData.time" type="date" placeholder="选择日期" size="default" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="submitHandler">
                    {{data?'保存':'新增'}}
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang='ts' setup>
import type { IUserTableItem } from '@/interfaces/IUser';
import { reactive,watch } from 'vue';
const emits=defineEmits(['save'])
const props=defineProps(["data"])
const visible = defineModel({ required: true })
const originFormData = {
    id: null,
    username: "",
    phonenumber: "",
    player: "",
    manager: "",
    land: "",
    time: "",
}

const formData = reactive({
        ...originFormData
})
watch(()=>props.data,(value)=>{
    if(value){
        Object.assign(formData, {
          ...value,
          land: Array.isArray(value.land) ? value.land.join('，') : value.land,
        });
    }else{
        Object.assign(formData, originFormData)
    }
})
const submitHandler=()=>{
        // 时间格式化
        if (formData.time && typeof formData.time === 'object' && 'toLocaleDateString' in formData.time) {
            formData.time = (formData.time as Date).toLocaleDateString().replace(/\//g, '.')
        }
        // 地块转为数组
        let landArr: string[] = [];
        if (typeof formData.land === 'string') {
            landArr = formData.land.split('，').map((l: string) => l.trim()).filter(Boolean);
        } else if (Array.isArray(formData.land)) {
            landArr = formData.land;
        }
        const submitData = {
            ...formData,
            land: landArr
        }
        visible.value=false;
        emits("save", submitData, props.data == null)
}
</script>

<style lang='scss' scoped></style>